﻿using Abp.AspNetCore;
using Abp.BackgroundJobs;
using Abp.Dependency;
using Abp.Extensions;
using Paas.Infrastructure.Data.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Basefr.Auth.Configurers;
using Basefr.Consts;
using Basefr.Data.EntityFrameworkCore;
using Basefr.Web.Data;
using Basefr.Web.Filters;
using System;
using System.Linq;
using Microsoft.OpenApi.Models;

namespace Paas.Svc.Host
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //跨域调用规则
            services.AddCors(options =>
            {
                //自用
                options.AddPolicy("Paas", builder =>
                {
                    builder.AllowAnyHeader();
                    builder.AllowAnyMethod();
                    builder.AllowCredentials();
                    builder.WithOrigins(Configuration["Cors:Origins"].Split(',', StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim().RemovePostFix("/")).ToArray());
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.AddService<HttpGlobalExceptionFilter>(1);  //注入自定义ExceptionFilter
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddNewtonsoftJson();

            //设置请求消息大小限制
            services.Configure<FormOptions>(options =>
            {
                options.ValueLengthLimit = 512 * 1024 * 1024;
                options.MultipartBodyLengthLimit = 512 * 1024 * 1024;
            });

            //数据库
            //sqlserver
            services.AddDbContext<MainDbContext>(options => { options.UseSqlServer(Configuration[ConnectionStringNames.Main]); });
            services.AddDbContext<AuditingDbContext>(options => options.UseSqlServer(Configuration[ConnectionStringNames.AuditLog]));
            //mysql
            //services.AddDbContext<MainDbContext>(options => { options.UseMySQL(Configuration[ConnectionStringNames.Main]); });
            //services.AddDbContext<AuditingDbContext>(options => options.UseMySQL(Configuration[ConnectionStringNames.AuditLog]));

            JwtBearerAuthConfigurer.Configure(services, Configuration);

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1",
                    new OpenApiInfo
                    {
                        Title = "AbpDemo",
                        Version = "v1",
                        Description = "",
                        TermsOfService = new Uri("https://github.com/ludewig"),
                        Contact = new OpenApiContact { Name = "ludewig", Email = "panshuairg@hotmail.com", Url = new Uri("https://github.com/ludewig") }
                    });
                options.DocInclusionPredicate((docName, description) => true);
                options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

            });

            return services.AddAbp<Module>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseAbp();

            app.MigrateDatabase<MainDbContext>(MainDbInitializer.Initializer(env));
            app.CreateDatabase<AuditingDbContext>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors("Paas");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Demo API v1");
            });
        }
    }
}

